import openpyxl
import os
import platform
from openpyxl.styles import Alignment, Font, Border, Side
from openpyxl.utils import get_column_letter

class ExcelHandler:
    def __init__(self, file_path):
        self.file_path = file_path
        self.wb = openpyxl.Workbook()
        self.wb.remove(self.wb.active)
        self.current_row = {}
        self.column_widths = {
            1: 12,  # 序号列
            2: 25,  # 测试点
            3: 40,  # 操作说明
            4: 30,  # 期望结果
            5: 30  # 实际结果
        }
        self.border_style = Border(
            left=Side(style='thin'),
            right=Side(style='thin'),
            top=Side(style='thin'),
            bottom=Side(style='thin')
        )

    def create_sheet(self, sheet_name,precondition_input):
        """创建基础sheet结构"""
        ws = self.wb.create_sheet(title=sheet_name[:31])

        # 仅填充基础数据，不设置样式
        template_headers = [
            ["测试用例名称", sheet_name+"测试", "", "", ""],
            ["测试用例标识", "", "", "", ""],
            ["测试说明", "", "", "", ""],
            ["前提条件", "", "", "", ""],
            ["测试过程", "", "", "", ""],
            ["序号", "测试点", "输入及操作说明", "期望测试结果", "实际测试结果"]
        ]

        for row_data in template_headers:
            ws.append(row_data)

        # 合并单元格
        for row in range(1, 6):
            start_col = 1 if row == 5 else 2
            ws.merge_cells(start_row=row, start_column=start_col, end_row=row, end_column=5)

        #添加前提条件
        ws.cell(row=4, column=2, value=precondition_input)

        self.current_row[sheet_name] = 7

    def apply_formatting(self):
        """统一应用格式到所有sheet"""
        for ws in self.wb.worksheets:
            # 设置列宽
            for col, width in self.column_widths.items():
                ws.column_dimensions[get_column_letter(col)].width = width * (2 if col == 1 else 0.9)

            # 应用表头样式
            for row in range(1, 7):
                for col in range(1, 6):
                    cell = ws.cell(row=row, column=col)
                    cell.border = self.border_style
                    cell.font = Font(bold=True)
                    cell.alignment = Alignment(horizontal="center", vertical="center")

            # 应用数据行样式
            for row in range(7, ws.max_row + 1):
                for col in range(1, 6):
                    cell = ws.cell(row=row, column=col)
                    cell.border = self.border_style
                    cell.alignment = Alignment(
                        wrap_text=True,
                        vertical='top',
                        horizontal='center' if col == 1 else 'general'  # 仅第一列居中
                    )

    def add_case(self, sheet_name, test_point, operation, expected_result="", actual_result=""):
        """添加测试用例数据"""
        if sheet_name not in self.current_row:
            self.create_sheet(sheet_name)

        ws = self.wb[sheet_name]
        row = self.current_row[sheet_name]

        ws.cell(row=row, column=1, value=row - 6)
        ws.cell(row=row, column=2, value=test_point)
        ws.cell(row=row, column=3, value=operation)
        ws.cell(row=row, column=4, value=expected_result)
        ws.cell(row=row, column=5, value=actual_result)

        self.current_row[sheet_name] += 1

    def save(self):
        """保存前统一应用格式"""
        self.apply_formatting()
        self.wb.save(self.file_path)

    def open_file(self):
        """打开生成的Excel文件"""
        if platform.system() == "Windows":
            os.startfile(self.file_path)
        elif platform.system() == "Darwin":
            os.system(f'open "{self.file_path}"')
        else:
            os.system(f'xdg-open "{self.file_path}"')
